package com.ruoyi.financial.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.financial.domain.*;
import com.ruoyi.financial.service.IFEnterService;
import com.ruoyi.financial.service.IFOutboundService;
import com.ruoyi.financial.service.IFThingService;
import com.ruoyi.financial.service.IFThingTypeService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 入库管理Controller
 *
 * @author xunzhe
 * @date 2024-01-31
 */
@Controller
@RequestMapping("/financial/fEnter")
public class FEnterController extends BaseController {
    private String prefix = "financial/fEnter";

    @Autowired
    private IFEnterService fEnterService;

    @Autowired
    private IFThingService fThingService;

    @Autowired
    private IFThingTypeService fThingTypeService;

    @Autowired
    private IFOutboundService ifOutboundService;

    @Autowired
    private ISysPostService postService;

    @RequiresPermissions("financial:fEnter:view")
    @GetMapping()
    public String fEnter(ModelMap mmap) {
        return prefix + "/fEnter";
    }

    /**
     * 查询入库管理列表
     */
    @RequiresPermissions("financial:fEnter:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FEnter fEnter) {
        startPage();
        List<FEnter> list = fEnterService.selectFEnterList(fEnter);
        return getDataTable(list);
    }

    /**
     * 导出入库管理列表
     */
    @RequiresPermissions("financial:fEnter:export")
    @Log(title = "入库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FEnter fEnter) throws Exception {
        List<FEnter> list = fEnterService.selectFEnterList(fEnter);
        ExcelUtil<FEnter> util = new ExcelUtil<FEnter>(FEnter.class);

        String title = "";
        if(fEnter.getDeptId()!=null && list.size()>0){
            title = list.get(0).getDeptName();
        }
        if(fEnter.getParams()!=null && fEnter.getParams().get("thingId")!=null && !fEnter.getParams().get("thingId").toString().equals("") && list.size()>0){
            FThing thing = fThingService.selectFThingByThingId(Long.parseLong(fEnter.getParams().get("thingId").toString()));
            title = title + thing.getThingName();

        }
        if(fEnter.getThingTypeId()!=null && list.size()>0){
            FThingType fThingType = fThingTypeService.selectFThingTypeByTypeId(fEnter.getThingTypeId());
            title = title + fThingType.getTypeName();
        }

        return util.exportExcel(list, "入库记录",title);
    }

    /**
     * 新增入库管理
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存入库管理
     */
    @RequiresPermissions("financial:fEnter:add")
    @Log(title = "入库管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(FEnter fEnter) {
        fEnter.setCreateBy(getLoginName());
        fEnter.setDeptId(getSysUser().getDeptId());

        List<SysPost> sysPosts = postService.selectPostsByUserId(getSysUser().getUserId());
        for (SysPost post : sysPosts) {
            if (post.isFlag()) {
                fEnter.setPostId(post.getPostId());
            }
        }
        if (fEnter.getThingId() != null) {
            FThing pThing = fThingService.selectFThingByThingId(fEnter.getThingId());
            if(pThing != null){
                fEnter.setAncestors(pThing.getAncestors());
            }
        }

        String danjia = fEnterService.selectAverageDanjia(fEnter);
        fEnter.setAverageDanjia(danjia);

        return toAjax(fEnterService.insertFEnter(fEnter));
    }

    /**
     * 修改入库管理
     */
    @RequiresPermissions("financial:fEnter:edit")
    @GetMapping("/edit/{enterId}")
    public String edit(@PathVariable("enterId") Long enterId, ModelMap mmap) {
        FEnter fEnter = fEnterService.selectFEnterByEnterId(enterId);
        mmap.put("fEnter", fEnter);
        return prefix + "/edit";
    }

    /**
     * 修改保存入库管理
     */
    @RequiresPermissions("financial:fEnter:edit")
    @Log(title = "入库管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FEnter fEnter) {
        fEnter.setUpdateBy(getLoginName());
        if (fEnter.getThingId() != null) {
            FThing pThing = fThingService.selectFThingByThingId(fEnter.getThingId());
            if(pThing != null){
                fEnter.setAncestors(pThing.getAncestors());
            }
        }
        String danjia = fEnterService.selectAverageDanjia(fEnter);
        fEnter.setAverageDanjia(danjia);

        return toAjax(fEnterService.updateFEnter(fEnter));
    }

    /**
     * 删除入库管理
     */
    @RequiresPermissions("financial:fEnter:remove")
    @Log(title = "入库管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(fEnterService.deleteFEnterByEnterIds(ids));
    }

    /**
     * 详细信息
     */
    @RequiresPermissions("financial:fEnter:detail")
    @GetMapping("/detail/{enterId}")
    public String detail(@PathVariable("enterId") Long enterId, ModelMap mmap) {
        FEnter fEnter = fEnterService.selectFEnterByEnterId(enterId);
        mmap.put("fEnter", fEnter);
        return prefix + "/detail";
    }

    /**
     * 首页当月总出和入库次数
     */
    @GetMapping("/byDateNumber")
    @ResponseBody
    public AjaxResult byDateNumber() {
        Map map = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String dateStr = sdf.format(new Date());
        map.put("deptId", getSysUser().getDeptId());
        map.put("yearStr", dateStr.split("-")[0]);
        map.put("monthStr", dateStr.split("-")[1]);
        int outNumber = ifOutboundService.selectCountByDate(map);
        int enterNumber = fEnterService.selectCountByDate(map);

        Map returnMap = new HashMap();
        returnMap.put("outNumber", outNumber);
        returnMap.put("enterNumber", enterNumber);

        return AjaxResult.success("查询成功", returnMap);
    }

    @RequiresPermissions("financial:fEnter:kucun")
    @GetMapping("/kucun")
    public String fEnterKucun(ModelMap mmap) {
        mmap.put("myDeptId", getSysUser().getDeptId());
        return prefix + "/fKucun";
    }

    /**
     * 查询库存列表
     */
    @PostMapping("/kucunList")
    @ResponseBody
    public TableDataInfo kucunList(FEnter fEnter) {
//        if(fEnter.getDeptId()==null){
//            fEnter.setDeptId(getSysUser().getDeptId());
//        }
        startPage();
        List<FEnter> list = fEnterService.selectFEnterKucun(fEnter);
        return getDataTable(list);
    }

    @RequiresPermissions("financial:fEnter:kucunexport")
    @PostMapping("/kucunexport")
    @ResponseBody
    public AjaxResult kucunexport(FEnter fEnter)
    {
        List<FEnter> list = fEnterService.selectFEnterKucun(fEnter);
        List<FKucun> kucunList = new ArrayList<>();
        for(FEnter data : list){
            FKucun kucun = new FKucun();
            kucun.setDeptName(data.getDeptName());
            kucun.setThingName(data.getThingName());
            kucun.setThingType(data.getThingType());
            kucun.setCreateName(data.getCreateName());
            kucun.setMohu(data.getMohu());
            kucun.setShuliang(data.getShuliang());
            kucun.setZonge(data.getZonge());
            kucun.setAverageDanjia(data.getAverageDanjia());
            kucun.setChushuliang(data.getChushuliang());
            kucun.setRenjunxiaohao(data.getRenjunxiaohao());
            kucun.setKucunshuliang(data.getKucunshuliang());
            kucunList.add(kucun);
        }

        ExcelUtil<FKucun> util = new ExcelUtil<FKucun>(FKucun.class);

        String title = "";
        if(fEnter.getDeptId()!=null && list.size()>0){
            title = list.get(0).getDeptName();
        }
        if(fEnter.getParams()!=null && fEnter.getParams().get("thingId")!=null && !fEnter.getParams().get("thingId").toString().equals("") && list.size()>0){
            FThing thing = fThingService.selectFThingByThingId(Long.parseLong(fEnter.getParams().get("thingId").toString()));
            title = title + thing.getThingName();

        }
        if(fEnter.getThingTypeId()!=null && list.size()>0){
            FThingType fThingType = fThingTypeService.selectFThingTypeByTypeId(fEnter.getThingTypeId());
            title = title + fThingType.getTypeName();
        }

        return util.exportExcel(kucunList, "库存列表",title);
    }

    @RequiresPermissions("financial:fEnter:shenpi")
    @GetMapping("/examine/{enterId}")
    public String examine(@PathVariable("enterId") Long enterId, ModelMap mmap) {
        FEnter fEnter = fEnterService.selectFEnterByEnterId(enterId);
        mmap.put("fEnter", fEnter);
        return prefix + "/examine";
    }

    @RequiresPermissions("financial:fEnter:shenpi")
    @Log(title = "入库管理", businessType = BusinessType.UPDATE)
    @PostMapping("/examineSave")
    @ResponseBody
    public AjaxResult examineSave(FEnter fEnter) {
        FEnter newFEnter = new FEnter();
        newFEnter.setEnterId(fEnter.getEnterId());
        newFEnter.setExamineStatus(fEnter.getExamineStatus());
        newFEnter.setExamineRemark(fEnter.getExamineRemark());
        newFEnter.setExamineBy(getLoginName());

        return toAjax(fEnterService.examine(newFEnter));
    }

    @GetMapping("/selectAverageDanjia/{thingId}/{thingType}")
    @ResponseBody
    public AjaxResult selectAverageDanjia(@PathVariable("thingId") Long thingId, @PathVariable("thingType") String thingType) {
        FEnter enter = new FEnter();
        enter.setThingId(thingId);
        enter.setThingType(thingType);
        enter.setParams(new HashMap<>());
        String danjia = fEnterService.selectAverageDanjia(enter);
        FThing fThing = fThingService.selectFThingByThingId(thingId);
        Map map = new HashMap();
        map.put("danjia", danjia);
        map.put("thingUnit", fThing.getThingUnit());
        return AjaxResult.success("查询成功", map);
    }
    @GetMapping("/ccc")
    public void ccc(HttpServletResponse response) throws Exception {
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        OutputStream out = null;
        Workbook wb = ExcelUtil.pivot(response);
        try {
            // 通过流将excel写出
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            wb.write(bos);
            byte[] bytes = bos.toByteArray();
            // 获取输出流
            out = response.getOutputStream();
            // 设置头信息
            response.setContentLength(bytes.length);
            response.setHeader("Content-disposition", "attachment;filename="
                    + new String("ceshi".getBytes("GBK"), "ISO8859-1"));
            // 通过流将excel写出
            wb.write(out);
            wb.close();
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<FEnterInData> util = new ExcelUtil<FEnterInData>(FEnterInData.class);
        return util.importTemplateExcel("入库数据");
    }

    @Log(title = "入库管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("financial:fEnter:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<FEnter> util = new ExcelUtil<FEnter>(FEnter.class);
        List<FEnter> list = util.importExcel(file.getInputStream());

        Long postId = 0L;
        List<SysPost> sysPosts = postService.selectPostsByUserId(getSysUser().getUserId());
        for (SysPost post : sysPosts) {
            if (post.isFlag()) {
                postId = post.getPostId();
            }
        }

        String message = fEnterService.importEnter(list, ShiroUtils.getSysUser(), postId);
        return AjaxResult.success(message);
    }


    public static void main(String[] args) {
        String str = "100";
        System.out.println();

    }


}
